<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<template>
  <div class="user-edit">
    <div class="user-edit-content">
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-width="auto"
        style="max-width: 600px"
        :rules="rules"
      >
        <el-form-item label="账号名" prop="name">
          <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" clearable :disabled="!editOrAdd" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            clearable
            v-model="form.password"
            show-password
          />
        </el-form-item>
        <!-- <el-form-item label="密码确认" prop="surePassword">
          <el-input
            type="password"
            clearable
            v-model="form.surePassword"
            show-password
          />
        </el-form-item> -->
        <el-form-item label="机构" prop="userOrg">
          <el-select v-model="form.orgId" clearable>
            <el-option
              v-for="item in orgList"
              :key="item.id"
              :label="item.orgName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" prop="dataPermission">
          <el-select v-model="form.dataPermission">
            <el-option label="本机构" :value="1" />
            <el-option label="所有机构" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联机构">
          <el-table
            :data="form.subOrgIdsAndNames"
            style="width: 100%"
            max-height="250"
          >
            <el-table-column fixed prop="id" label="机构id" width="120" />
            <el-table-column prop="orgName" label="机构全称" width="280" />
            <el-table-column fixed="right" label="操作" min-width="100">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.prevent="deleteRow(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="mt-4" style="width: 100%" @click="onAddItem">
            添加
          </el-button>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group
            v-model="form.roleIds"
            style="display: flex; flex-wrap: wrap"
          >
            <el-checkbox
              :value="item.id"
              name="type"
              v-for="(item, index) in roleList"
              :key="index"
            >
              {{ item.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div class="user-edit-botton">
          <el-form-item>
            <el-button
              color="rgb(222, 41, 16)"
              type="primary"
              @click="submitForm(ruleFormRef)"
              >保存</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <el-drawer v-model="drawer" title="选择机构" direction="rtl" size="50%">
      <el-table
        :data="currentOrgList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="id" label="id" />
        <el-table-column property="orgName" label="机构名称" />
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router"; // 引入useRouter函数
import http from "@/request/request";
import { Md5 } from "ts-md5";

const router = useRouter(); // 获取路由实例
const route = useRoute();
//-----------------------------------------参数定义------------------------//
interface SubOrgInfo {
  id?: number; // id
  orgName: string; // 机构名称
}
interface UserForm {
  name: string;
  phone: string;
  password: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  orgId: any;
  state: number;
  roleIds: number[];
  dataPermission: number;
  subOrgIdsAndNames: SubOrgInfo[];
}
interface Role {
  id: number;
  roleName: string;
}

interface Org {
  id: number;
  orgName: string;
}
// form表单
const form = ref<UserForm>({
  name: "",
  phone: "",
  password: "",
  orgId: "",
  state: 1,
  roleIds: [],
  dataPermission: 1,
  subOrgIdsAndNames: [],
});

// 机构列表
const orgList = ref<Org[]>();
const roleList = ref<Role[]>();
const ruleFormRef = ref<FormInstance>();

const drawer = ref(false);
const subOrgList = ref<SubOrgInfo[]>([]);
const currentOrgList = ref<SubOrgInfo[]>([]);

const rules = reactive<FormRules<UserForm>>({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    {
      required: true,
      message: "请输入手机号",
    },
    {
      pattern:
        /^1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
    },
  ],
  password: [
    { required: true, message: "请输入密码" },
    { min: 8, max: 20, message: "密码长度要在8-20个字符中间" },
  ],
  orgId: [{ required: true, message: "请选择机构" }],
});
const editOrAdd = ref(true);
//-----------------------------------------方法定义------------------------//

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const md5: any = new Md5();
      md5.appendAsciiStr(form.value.password);
      form.value.password = md5.end();
      if (editOrAdd.value) {
        addUser();
      } else {
        updateUser();
      }
      router.push("/user");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.back();
};
// 查询所有角色列表
const getAllRoleList = async () => {
  try {
    const { data } = await http.get<Role[]>("/api/system/getAllRoleList");
    roleList.value = data;
  } catch (err) {
    console.log(err);
  }
};
// 新增用户信息
const addUser = async () => {
  try {
    await http.post<Role[]>("/api/system/addUser", form.value);
  } catch (err) {
    console.log(err);
  }
};
// 查询用户详情
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getUserDetail = async (id: any) => {
  try {
    const { data } = await http.get<UserForm>("/api/system/getUserDetail", {
      userId: id,
    });
    form.value = data;
    form.value.password = "********";
  } catch (err) {
    console.log(err);
  }
};
// 修改用户信息
const updateUser = async () => {
  try {
    await http.post<Role[]>("/api/system/updateUser", form.value);
  } catch (err) {
    console.log(err);
  }
};
// 查询机构列表
const getAllOrgList = async () => {
  try {
    const { data } = await http.get<Org[]>("/api/system/getEnabledOrgList");
    orgList.value = data;
    subOrgList.value = data;
  } catch (err) {
    console.log(err);
  }
};

// 添加资产方
const onAddItem = () => {
  drawer.value = true;
  if (form.value.subOrgIdsAndNames) {
    console.log(form.value.subOrgIdsAndNames);
    currentOrgList.value = subOrgList.value.filter(
      (item) => !form.value.subOrgIdsAndNames.map((i) => i.id).includes(item.id)
    );
    console.log(currentOrgList.value);
  } else {
    currentOrgList.value = subOrgList.value;
  }
};

// 批量选择
const handleSelectionChange = (val: SubOrgInfo[]) => {
  if (
    form.value.subOrgIdsAndNames === null ||
    form.value.subOrgIdsAndNames === undefined
  ) {
    form.value.subOrgIdsAndNames = [];
  }
  val.forEach((v) => {
    form.value.subOrgIdsAndNames.push(v);
  });
  form.value.subOrgIdsAndNames = uniqueByPropertyWithMap(
    form.value.subOrgIdsAndNames,
    "id"
  );
};
//
const deleteRow = (index: number) => {
  if (form.value.subOrgIdsAndNames) {
    form.value.subOrgIdsAndNames.splice(index, 1);
  }
};

// 使用Map根据属性去重[citation:1][citation:3]
function uniqueByPropertyWithMap<T>(arr: T[], key: keyof T): T[] {
  const map = new Map();
  arr.forEach((item) => {
    // 以对象的key属性值作为Map的键
    if (!map.has(item[key])) {
      map.set(item[key], item);
    }
  });
  return Array.from(map.values());
}
//-----------------------------生命周期-------------------------------//
onMounted(() => {
  const id = route.query.id;
  getAllRoleList();
  getAllOrgList();
  // 判断是否有参数传递，如果有参数传递，则进行请求接口，视为修改，否则视为添加
  if (id) {
    editOrAdd.value = false;
    getUserDetail(id);
  }
});
</script>

<style lang="less" scoped>
.user-edit {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  background-color: rgb(255, 255, 255);
  .user-edit-content {
    width: 60%;
    padding: 20px;
    padding-top: 50px;
  }
  .user-edit-botton {
    position: absolute;
    left: 65%;
    top: 85%;
    .el-button {
      width: 160px;
    }
  }
}
</style>